//===============================================================================
// Microsoft Architecture Strategy Team
// LitwareHR - SaaS Sample Application
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================



using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Principal;
using System.Runtime.InteropServices;

using LitwareHR.Portfolio.Contract;
using LitwareHR.Portfolio.Services.Properties;

namespace LitwareHR.Portfolio.Services
{
    public class WindowsIdentityImpersonate
    {
        WindowsImpersonationContext impersonationContext;

        public enum LogonType : int
        {
            Logon32LogonInteractive = 2,
            Logon32LogonNetwork = 3,
            Logon32LogonBatch = 4,
            Logon32LogonService = 5,
            Logon32LogonUnlock = 7,
            Logon32LogonNetworkClearText = 8,   // Only for Win2K or higher
            Logon32LogonNewCredentials = 9      // Only for Win2K or higher
        };

        public enum LogonProvider : int
        {
            Logon32ProviderDefault = 0,
            Logon32ProviderWinNT35 = 1,
            Logon32ProviderWinNT40 = 2,
            Logon32ProviderWinNT50 = 3
        };

        class NativeMethods
        {
            [DllImport("advapi32.dll", SetLastError = true)]
            internal static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
                        int dwLogonType, int dwLogonProvider, ref IntPtr TokenHandle);

            [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
            internal extern static bool CloseHandle(IntPtr handle);

            [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            internal extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
                        int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
        }

        public bool Impersonate(string userName, string domain, string password)
        {
            try
            {
                return ImpersonateValidUser(userName, domain, password);
            }
            catch (Exception ex)
            {
                throw new ProvisioningException(ex.Message, ex);
            }
        }

        public void Undo()
        {
            try
            {
                UndoImpersonation();
            }
            catch (Exception ex)
            {
                throw new ProvisioningException(ex.Message, ex);
            }
        }

        private bool ImpersonateValidUser(String userName, String domain, String password)
        {
            WindowsIdentity tempWindowsIdentity;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;
            try
            {
                if (NativeMethods.LogonUser(userName, domain, password,
                    (int)LogonType.Logon32LogonInteractive, (int)LogonProvider.Logon32ProviderDefault, ref token))
                {
                    if (NativeMethods.DuplicateToken(token, 2, ref tokenDuplicate))
                    {
                        tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                        impersonationContext = tempWindowsIdentity.Impersonate();
                        if (impersonationContext != null)
                        {
                            NativeMethods.CloseHandle(token);
                            NativeMethods.CloseHandle(tokenDuplicate);
                            return true;
                        }
                    }
                    else
                    {
                        throw new ApplicationException(Resources.DuplicateTokenFailed, null);
                    }
                }
                else
                {
                    int ret = Marshal.GetLastWin32Error();
                    string err = String.Format(Resources.LogonFailed, ret);
                    throw new ApplicationException(err, null);
                }
                return false;
            }
            finally
            {
                if (token != IntPtr.Zero)
                    NativeMethods.CloseHandle(token);
                if (tokenDuplicate != IntPtr.Zero)
                    NativeMethods.CloseHandle(tokenDuplicate);
            }
        }

        private void UndoImpersonation()
        {
            impersonationContext.Undo();
        }
    }
}
